# -*- coding: utf-8 -*-

class TwitPicKer(object):
	URL = 'twitpic.com'
	PORT = '80'
	SEND_TO = '/api/upload/'
	AGENT_TITLE = 'tweerminal'
	REQUEST_TYPE = 'POST'

	def __init__(self, user, psswd):
		self.user = user
		self.psswd = psswd
		self.img_path = None
		self.img_data = None
		
	def parse_xml(self,xml_response):
		from xml.dom import minidom as xml
		dom = xml.parseString(xml_response)
		node = dom.getElementsByTagName('rsp')
		if node[0].getAttribute('stat') == 'ok' or node[0].getAttribute('status') == 'ok':
			url = dom.getElementsByTagName('mediaurl')
			return 'ok', url[0].childNodes[0].data
		elif node[0].getAttribute('stat') == 'fail':
			childNode = node[0].childNodes[1]
			if childNode.getAttribute('code') == '1001':
				return '1001', 'Invalid twitter username or password'
			elif childNode.getAttribute('code') == '1002':
				return '1002', 'Image not found'
			elif childNode.getAttribute('code') == '1003':
				return '1003', 'Invalid image type'
			else:
				return '1004', 'Image larger than 4MB'
		return '0', 'Unidentified Error'
		
	def connect(self, url=URL, port=PORT):
		#Inicio de importaciones necesarias
		import httplib
		return httplib.HTTPConnection(url + ":" + port)

	def load_img(self):
		import urllib
		try:
			import cStringIO as StringIO
		except ImportError:
			import StringIO
		return StringIO.StringIO(urllib.urlopen(self.img_path).read())

	def create_multipart_form(self):
		import mimetypes
		# Creación de la forma multiparte
		boundary = '-------yOuShAlLnOtPaSsDoAsICoMmaNd'
		crlf = '\r\n'
		tmp = []
		for (key, value) in [('username',self.user),('password',self.psswd)]:
			tmp.append('--' + boundary)
			tmp.append('Content-Disposition: form-data; name="' + str(key) + '"')
			tmp.append('')
			tmp.append(str(value))
		for (filename, value) in [(self.img_path,self.img_data)]:
			tmp.append('--' + boundary)
			tmp.append('Content-Disposition: form-data; name="media"; filename="' + str(filename) + '"')
			tmp.append('Content-Type: ' + str(mimetypes.guess_type(filename)[0]) or 'application/octet-stream')
			tmp.append('')
			tmp.append(value.getvalue())
		tmp.append('--' + boundary + '--')
		tmp.append('')
		content = crlf.join(tmp)
		c_type = 'multipart/form-data; boundary=' + boundary
		return content, c_type

	def upload(self, img_path, agent_title=AGENT_TITLE, request_type=REQUEST_TYPE, send_to=SEND_TO):
		connection = self.connect()
		self.img_path = img_path
		self.img_data = self.load_img()
		content, c_type = self.create_multipart_form()
		
		# Envío de datos
		c_headers = {'User-Agent': agent_title, 'Content-Type': c_type}
		connection.request(request_type, send_to, content, c_headers)
		response = connection.getresponse()
		if response.status != 200:
			return str(response.status), str(response.reason)
		else:
			return self.parse_xml(response.read())
		
